package com.ctms.system.controller;

import com.ctms.common.utils.PageUtils;
import com.ctms.common.utils.Query;
import com.ctms.common.utils.R;
import com.ctms.common.utils.ShiroUtils;
import com.ctms.system.domain.*;
import com.ctms.system.service.CorrectsTaskService;
import com.ctms.system.service.ShiPinService;
import com.ctms.system.service.TaskReleaseService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping("/task_release")
@Controller
public class TaskReleaseController {
    @Autowired
    TaskReleaseService taskReleaseService;
    @Autowired
    CorrectsTaskService correctsTaskService;

    @GetMapping("")
    public String task(){
        return "/sys/taskRelease/taskRelease";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String,Object> params){
        //登录人姓名
        UserDO userDO = ShiroUtils.getUser();
        String name = userDO.getName();
        params.put("name",name);

        Query query = new Query(params);
        List<TaskReleaseDO> taskReleaseDOS = taskReleaseService.selectAllTask(params);
        int total = taskReleaseService.count(query);
        PageUtils pageUtils = new PageUtils(taskReleaseDOS,total);
        return pageUtils;
    }

   @GetMapping("/add")
   public String add(){
       return "/sys/taskRelease/add";
   }

    @PostMapping("/save")
    @ResponseBody
    R insertTask(TaskReleaseDO taskReleaseDO){
        UserDO userDO = ShiroUtils.getUser();
        String name = userDO.getName();
        taskReleaseDO.setTaskReleaseTeacher(name);
        int courseId = Integer.parseInt(taskReleaseDO.getTaskCourse());
        String courseName = taskReleaseService.getCourseNameById(courseId);
        taskReleaseDO.setTaskCourse(courseName);
        if (taskReleaseService.insertTask(taskReleaseDO)>0){
            //查找最大的tid
            int tid = taskReleaseService.selectMaxTid();
            //这门课所有的学生信息
            List<UserDO> userDOS = correctsTaskService.selectUserByCid(courseId);
            //插入任务打分表
            for (int i=0;i<userDOS.size();i++){
                CorrectsTaskDO correctsTaskDO = new CorrectsTaskDO();
                correctsTaskDO.setTid(tid);
                int user_id = Integer.parseInt(Long.toString(userDOS.get(i).getUserId()));
                correctsTaskDO.setUserId(user_id);
                correctsTaskDO.setEmail(userDOS.get(i).getEmail());
                correctsTaskDO.setStudentClass(userDOS.get(i).getStudentClass());
                correctsTaskDO.setName(userDOS.get(i).getName());
                correctsTaskDO.setUsername(userDOS.get(i).getUsername());
                correctsTaskService.insertCorrectsTask(correctsTaskDO);
            }
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/edit/{tid}")
    public String edit(Model model, @PathVariable("tid")Integer tid) throws Exception {
        TaskReleaseDO taskReleaseDO = taskReleaseService.selectTaskByTid(tid);
        //处理时间显示多个0的问题
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = format.parse(taskReleaseDO.getTaskReleaseTime());
        String create = format.format(date1);
        Date date2 = format.parse(taskReleaseDO.getTaskEndTime());
        String end = format.format(date2);
        taskReleaseDO.setTaskReleaseTime(create);
        taskReleaseDO.setTaskEndTime(end);
        model.addAttribute("task",taskReleaseDO);
        return "sys/taskRelease/edit";
    }

    @PostMapping("/update")
    @ResponseBody
    R update(TaskReleaseDO taskReleaseDO){
        if (taskReleaseService.updateTask(taskReleaseDO)>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @PostMapping("/remove")
    @ResponseBody
    R deleteTask(Integer tid){
        if (taskReleaseService.deleteTask(tid)>0){
            correctsTaskService.deleteCorrectsTask(tid);
            correctsTaskService.deleteCommitTask(tid);
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/showFile/{name}")
    public String showFile(Model model,@PathVariable("name")String name){
        String[] filename = name.split(",");
        //文件访问路径
       String result = "";
        for (int i=0;i<filename.length;i++){
            ShipinDO shipinDO = taskReleaseService.selectFileByName(filename[i]);
            if (i == filename.length-1){
                result = result + shipinDO.getUrl();
            }else {
                result = result + shipinDO.getUrl() + ",";
            }
        }
        model.addAttribute("fileUrl",result);
        model.addAttribute("fileName",name);
        return "sys/taskRelease/fileList";
    }

    @PostMapping("/getCourse")
    @ResponseBody
    public List<CourseDO> getCourse(){
        UserDO userDO = ShiroUtils.getUser();
        int userId = Integer.parseInt(Long.toString(userDO.getUserId()));
        List<CourseDO> list = taskReleaseService.getAllCourse(userId);
        return list;
    }

   /* //通过文件名查找文件url
    @PostMapping("/getFileUrl")
    @ResponseBody
    public List<String> getFileUrl(String fileName){
        String[] file = fileName.split(",");
        List<String> result=new ArrayList<>();
        for (int i=0;i<file.length;i++){
            ShipinDO shipinDO = taskReleaseService.selectFileByName(file[i]);
            result.add(shipinDO.getUrl());
        }
        return result;
    }*/

}
